// 消息管理云对象
module.exports = {
	_before: function () {
		// 通用预处理器
		this.startTime = Date.now();
	},

	/**
	 * 获取用户消息列表
	 * @param {string} type 消息类型（可选）
	 * @param {number} page 页码
	 * @param {number} limit 每页数量
	 * @returns {object} 消息列表
	 */
	async getMessageList({type, page = 1, limit = 20}) {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		
		if (!userId) {
			return {
				errCode: 401,
				errMsg: '用户未登录'
			}
		}

		try {
			const db = uniCloud.database();
			
			let whereCondition = {
				user_id: userId
			};
			
			if (type) {
				whereCondition.type = type;
			}
			
			// 分页查询
			const skip = (page - 1) * limit;
			const messageResult = await db.collection('sh_user_message')
				.where(whereCondition)
				.orderBy('create_time', 'desc')
				.skip(skip)
				.limit(limit)
				.get();
			
			// 获取总数和未读数量
			const [countResult, unreadResult] = await Promise.all([
				db.collection('sh_user_message').where(whereCondition).count(),
				db.collection('sh_user_message').where({
					user_id: userId,
					is_read: false
				}).count()
			]);

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: {
					list: messageResult.data,
					total: countResult.total,
					unreadCount: unreadResult.total,
					page,
					limit,
					totalPages: Math.ceil(countResult.total / limit)
				}
			}
		} catch (error) {
			console.error('获取消息列表失败:', error);
			return {
				errCode: 'GET_MESSAGE_LIST_FAILED',
				errMsg: '获取消息列表失败'
			}
		}
	},

	/**
	 * 标记消息为已读
	 * @param {string} userId 用户ID
	 * @param {string} messageId 消息ID
	 * @returns {object} 标记结果
	 */
	async markAsRead({userId, messageId}) {
		if (!userId || !messageId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 检查消息权限并更新
			const updateResult = await db.collection('sh_user_message').where({
				_id: messageId,
				user_id: userId
			}).update({
				is_read: true,
				read_time: new Date()
			});

			if (updateResult.updated === 0) {
				return {
					errCode: 'MESSAGE_NOT_FOUND',
					errMsg: '消息不存在或无权限'
				}
			}

			return {
				errCode: 0,
				errMsg: '标记成功'
			}
		} catch (error) {
			console.error('标记消息已读失败:', error);
			return {
				errCode: 'MARK_READ_FAILED',
				errMsg: '标记消息已读失败'
			}
		}
	},

	/**
	 * 批量标记消息为已读
	 * @param {array} messageIds 消息ID列表
	 * @returns {object} 标记结果
	 */
	async batchMarkAsRead({messageIds}) {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		
		if (!userId || !Array.isArray(messageIds) || messageIds.length === 0) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			const dbCmd = db.command;
			
			// 批量更新
			const updateResult = await db.collection('sh_user_message').where({
				_id: dbCmd.in(messageIds),
				user_id: userId
			}).update({
				is_read: true,
				read_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '批量标记成功',
				data: {
					updated: updateResult.updated
				}
			}
		} catch (error) {
			console.error('批量标记消息已读失败:', error);
			return {
				errCode: 'BATCH_MARK_READ_FAILED',
				errMsg: '批量标记消息已读失败'
			}
		}
	},

	/**
	 * 删除消息
	 * @param {string} messageId 消息ID
	 * @returns {object} 删除结果
	 */
	async deleteMessage({messageId}) {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		
		if (!userId || !messageId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 检查消息权限并删除
			const deleteResult = await db.collection('sh_user_message').where({
				_id: messageId,
				user_id: userId
			}).remove();

			if (deleteResult.deleted === 0) {
				return {
					errCode: 'MESSAGE_NOT_FOUND',
					errMsg: '消息不存在或无权限'
				}
			}

			return {
				errCode: 0,
				errMsg: '删除成功'
			}
		} catch (error) {
			console.error('删除消息失败:', error);
			return {
				errCode: 'DELETE_MESSAGE_FAILED',
				errMsg: '删除消息失败'
			}
		}
	},

	/**
	 * 发送系统消息
	 * @param {string} userId 接收用户ID
	 * @param {string} type 消息类型
	 * @param {string} title 消息标题
	 * @param {string} content 消息内容
	 * @param {object} data 附加数据
	 * @param {number} priority 优先级
	 * @returns {object} 发送结果
	 */
	async sendSystemMessage({userId, type, title, content, data, priority = 1}) {
		if (!userId || !type || !content) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 创建消息
			const messageResult = await db.collection('sh_user_message').add({
				user_id: userId,
				type,
				title: title || '',
				content,
				data: data || {},
				is_read: false,
				priority,
				create_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '发送成功',
				data: {
					messageId: messageResult.id
				}
			}
		} catch (error) {
			console.error('发送系统消息失败:', error);
			return {
				errCode: 'SEND_MESSAGE_FAILED',
				errMsg: '发送系统消息失败'
			}
		}
	},

	/**
	 * 获取未读消息数量
	 * @param {string} userId 用户ID
	 * @returns {object} 未读数量
	 */
	async getUnreadCount({userId}) {
		if (!userId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '用户ID不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			const unreadResult = await db.collection('sh_user_message').where({
				user_id: userId,
				is_read: false
			}).count();

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: {
					unreadCount: unreadResult.total
				}
			}
		} catch (error) {
			console.error('获取未读消息数量失败:', error);
			return {
				errCode: 'GET_UNREAD_COUNT_FAILED',
				errMsg: '获取未读消息数量失败'
			}
		}
	},

	/**
	 * 全部标记为已读
	 * @returns {object} 标记结果
	 */
	async markAllAsRead() {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		
		if (!userId) {
			return {
				errCode: 401,
				errMsg: '用户未登录'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 全部标记为已读
			const updateResult = await db.collection('sh_user_message').where({
				user_id: userId,
				is_read: false
			}).update({
				is_read: true,
				read_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '全部标记成功',
				data: {
					updated: updateResult.updated
				}
			}
		} catch (error) {
			console.error('全部标记已读失败:', error);
			return {
				errCode: 'MARK_ALL_READ_FAILED',
				errMsg: '全部标记已读失败'
			}
		}
	}
}
